﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;

namespace VSM
{
    public partial class DocumentListStock : System.Web.UI.Page
    {
        private static string FromDocDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("dd/MM/yyyy");
        private static string ToDocDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToString("dd/MM/yyyy");
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                if (Request.QueryString["DocType"] != null && Request.QueryString["DocType"].Length > 0)
                {
                    if (!IsPostBack)
                    {
                       
                        hdnDocType.Value = Request.QueryString["DocType"];
                        ////Add By Hieu - 21/5/2014 - START
                        //this.hdnDepartment.Value = Session[Utils.AppConstants.U_Department].ToString(); // Request.QueryString["Depart"]; //thangnv editing 28/05/2013
                        ////Add By Hieu - 21/5/2014 - END
                        //// 
                        //if (Request.QueryString["TransferType"] != null && Request.QueryString["TransferType"].Length > 0) hdnTransferType.Value = Request.QueryString["TransferType"].ToString();

                        //if (Request.QueryString["Status"] != null && Request.QueryString["Status"].Length > 0)
                        //{
                        //    ddlStatus.SelectedValue = Request.QueryString["Status"];
                        //    ddlStatus.Enabled = false;
                        //}
                        //else
                        //{
                        //    ddlStatus.Enabled = true;
                        //    ddlStatus.SelectedIndex = 0;
                        //}
                        //if (Request.QueryString["PayNoDoc"] != null && Request.QueryString["PayNoDoc"].Length > 0)
                        //    hdnPayNoDoc.Value = Request.QueryString["PayNoDoc"];
                        //else hdnPayNoDoc.Value = String.Empty;

                        txtFromDocDate.Text = FromDocDate;
                        txtToDocDate.Text = ToDocDate;
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            LoadData();
            Timer1.Enabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdBP_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dt = Session["DocListTable"] as DataTable;
                if (dt != null)
                {
                    dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                    Session["DocListTable"] = dt.DefaultView.ToTable();
                    this.grdBP.DataSource = dt.DefaultView.ToTable();
                    this.grdBP.DataBind();
                }
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private string GetSortDirection(string column)
        {
            string sortDirection = "ASC";
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdBP_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = this.grdBP.SelectedRow;
                DataTable dt = (DataTable)Session["DocListTable"];
                if (dt != null)
                {
                    int index = row.DataItemIndex;
                    var data = dt.Rows[index];
                    if (data != null)
                    {
                        Session["ChosenCode"] = data["CardCode"];
                        Session["ChosenName"] = data["CardName"];
                        //ScriptManager.RegisterStartupScript(this, this.GetType(), "OK", "Main.okDialogClick('SelectBP');", true);
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdBP_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                    e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)"); 

                    e.Row.Attributes["style"] = "cursor:pointer";
                    e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdBP, "Select$" + e.Row.RowIndex);
                }
            }
            catch (Exception ex)
            {

            }
        }

        protected void btnFiletrRemark_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable tblDocList = (DataTable)Session["DocListTable"];
                if (tblDocList != null && this.txtRemark.Text.Trim().Length > 0)
                {
                    DataView dv = tblDocList.DefaultView;
                    if (!string.IsNullOrEmpty(this.txtRemark.Text.Trim()))
                        dv.RowFilter = "Comments like '%" + this.txtRemark.Text.Trim() + "%'";
                    else
                        dv.RowFilter = "";

                    this.grdBP.DataSource = dv.ToTable();
                    this.grdBP.DataBind();
                }
            }
            catch (Exception ex)
            { 
            
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            FromDocDate = txtFromDocDate.Text;
            ToDocDate = txtToDocDate.Text;
            LoadData();
            btnFiletrRemark_Click(null, null);
        }

        protected void btnAccept_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow selectedRow = this.grdBP.SelectedRow;
                if (selectedRow == null) return;
                /*Dictionary<string, string> dicBP = new Dictionary<string, string>();
                Label code = (Label)selectedRow.FindControl("lblCardCode");
                Label Name = (Label)selectedRow.FindControl("lblCardName");
                dicBP.Add(code.Text, Name.Text);*/

                /*Dictionary<string, string> dicBP = new Dictionary<string, string>();
                for (int i = 0; i < this.grdBP.Rows.Count; i++)
                {
                    CheckBox checkBox = (CheckBox)this.grdBP.Rows[i].FindControl("chkChild");

                    if (checkBox != null)
                    {
                        if (checkBox.Checked)
                        {
                            Label code = (Label)this.grdBP.Rows[i].FindControl("lblCardCode");
                            Label Name = (Label)this.grdBP.Rows[i].FindControl("lblCardName");
                            dicBP.Add(code.Text, Name.Text);
                        }
                    }
                }*/
                ((Label)selectedRow.FindControl("lblDocType")).Text = hdnDocType.Value; 
                Session["ChosenDocList"] = selectedRow;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "OK", "Main.okDialogClick('SelectDocList');", true);
            }
            catch (Exception ex)
            {

            }
        }

        private void LoadData()
        {
            try
            {
                GetDefault getDefault = new GetDefault();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Set default values ...
                DateTime fromDocDate = Utils.AppConstants.ConvertToDate((string.IsNullOrEmpty(txtFromDocDate.Text) ? "01/01/1900" : txtFromDocDate.Text));
                DateTime toDocDate = Utils.AppConstants.ConvertToDate((string.IsNullOrEmpty(txtToDocDate.Text) ? "31/12/9998" : txtToDocDate.Text));
                DateTime fromDueDate = Utils.AppConstants.ConvertToDate((string.IsNullOrEmpty(txtFromDueDate.Text) ? "01/01/1900" : txtFromDueDate.Text));
                DateTime toDueDate = Utils.AppConstants.ConvertToDate((string.IsNullOrEmpty(txtToDueDate.Text) ? "31/12/9998" : txtToDueDate.Text));

                string Condition = string.Empty;
                if (hdnDocType.Value.Equals("59-0"))
                    Condition = " and U_SOType = 0 ";
                else // 59-1
                    Condition = " and U_SOType = 1 ";

                DataTable dtDocList = null;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                string SLQCommand = "select ROW_NUMBER() Over(Order By U_stockcount_id) DocNum, U_stockcount_id, DocDate, DocDueDate, CardCode, CardName, Comments, DocTotal, DocStatus, U_SOType from OIGN where U_stockcount_id is not null " + Condition;
                SLQCommand += " union ";
                SLQCommand += "select ROW_NUMBER() Over(Order By U_stockcount_id) AS DocNum, U_stockcount_id, DocDate, DocDueDate, CardCode, CardName, Comments, DocTotal, DocStatus, U_SOType from OIGE where U_stockcount_id is not null " + Condition;

                dtDocList = GF.GetMasterListBySqlCommand(dbType, SLQCommand);

                //if(hdnPayNoDoc.Value.Equals(""))
                //      dsDocList = getDefault.GetDocumentList(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), 
                //        ddlCustomer.SelectedValue, hdnDocType.Value, txtFromDocNo.Text.Trim(), txtToDocNo.Text.Trim(), fromDocDate, toDocDate, fromDueDate, toDueDate,
                //        txtFromDocTotal.Text, txtToDocTotal.Text, ddlStatus.SelectedValue,this.hdnDepartment.Value,this.txtVSMSONumber.Text.Trim(),this.txtDebitNote.Text.Trim());
                //else
                //    dsDocList = getDefault.GetIncomingPaymentList(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), 
                //        ddlCustomer.SelectedValue, hdnDocType.Value, txtFromDocNo.Text.Trim(), txtToDocNo.Text.Trim(), fromDocDate, toDocDate, fromDueDate, toDueDate,
                //        txtFromDocTotal.Text, txtToDocTotal.Text, ddlStatus.SelectedValue, hdnPayNoDoc.Value, this.hdnDepartment.Value);

                if (dtDocList != null && dtDocList.Rows.Count > 0) BindDocList(dtDocList);
            }
            catch (Exception ex)
            { 
            
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void BindDocList(DataTable tb)
        {
            Session["DocListTable"] = tb;
            this.grdBP.DataSource = tb;
            this.grdBP.DataBind();
        }
    }
}